<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />
    <!-- 操作按钮区域 -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        :border='true'
        :resizable='true'
        :showOverflow='true'
        size='mini'
        :loading='loading'
        :height='pageHeight-seachHeight-94'
        :align='left'
        :columns='columns'
        :data='dataSource'
        :toolbar-config='tableToolbar'
        :checkbox-config='checkboxConfig'
        v-bind='vexConfig'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class='table-operator'>
            <a-button v-has="'cusProductGroups:add'" @click='handleAdd'>新增</a-button>
            <a-button v-has="'cusProductGroups:delete'" @click='batchDel'>删除</a-button>
            <a-button v-has="'cusProductGroups:export'"  @click=''>导出</a-button>
          </div>
        </template>


        <template #detail='{ row,rowIndex }'>
          <a @click='handleView(row)'>{{ row.productGroupCode }}</a>
        </template>

        <template #action='{ row,rowIndex }'>
          <a v-has="'cusProductGroups:update'" @click='handleEdit(row)'>编辑</a>
          <a-divider type='vertical' />
          <a v-has="'business:log'" href='javascript:' @click='handleBusiness("产品组",row)'>日志</a>
        </template>
        <template #update='{ row }'>
          <a-switch :checked='row.status==1' size='small' @change='changeStatus($event,row)' />
        </template>

        <template #pager>
          <vxe-pager
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :currentPage.sync='ipagination.current'
            :page-size.sync='ipagination.pageSize'
            :total='ipagination.total'
            :pageSizes='ipagination.pageSizeOptions'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>

    </div>
    <!-- table区域-end -->
    <business-log ref='businessLog'></business-log>

    <!-- 表单区域 -->
    <cus-product-modal ref='modalForm' @ok='modalFormOk'></cus-product-modal>

  </a-card>
</template>

<script>
import cusProductModal from './modules/CustProductModal'
import FormAddEdit from '@comp/view/base-crud/form/FormAddEdit'
import JSuperQuery from '@/components/cn-form/JSuperQuery.vue'
import JInput from '@/components/cn-form/JInput.vue'
import { initDictOptions, filterDictText, filterDictTextByCache } from '@/components/dict/CnDictSelectUtil'
import { PageListMixin } from '@/mixins/PageListMixin'
import Vue from 'vue'
import { filterObj } from '@/utils/util'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import { postAction } from '../../../api/manage'
// import materialModal from './modules/materialModal'
import { getAction } from '@/api/manage'
import search from '@comp/view/base-crud/search/Search'

//高级查询modal需要参数

export default {
  name: 'cusProductGroups',
  mixins: [PageListMixin],
  components: {
    JSuperQuery,
    JInput,
    JTreeSelect, cusProductModal,
    // materialModal,
    search
  },
  // priceAdd
  data() {
    return {
      description: '经销商可购清单',
      //字典数组缓存
      sexDictOptions: [],
      importExcelUrl: `${window._CONFIG['domianURL']}/test/cn-formDemo/importExcel`,

      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'productGroupCode',
          placeholder: '自定义产品组编号'
        },
        {
          type: 'input',
          name: 'productGroupName',
          placeholder: '自定义产品组名称'
        },
        {
          type: 'input',
          name: 'createName',
          placeholder: '创建人'
        },
        {
          type: 'date-range', //范围选择
          range: ['startDate', 'endDate'],
          name: 'range',
          format: 'YYYY-MM-DD',
          placeholder: ['创建时间', '创建时间']
        }],
      //表头
      columns: [],
      //列设置
      settingColumns: [],
      //列定义  表格改这儿
      defColumns: [
        // {
        //   title: '#',
        //   dataIndex: '',
        //   key: 'rowIndex',
        //   width: 60,
        //   align: 'center',
        //   customRender: function(t, r, index) {
        //     return parseInt(index) + 1
        //   }
        // },
        { type: 'checkbox', width: 60, fixed: 'left' },
        {
          fixed: 'left',
          minWidth: 120,
          title: '自定义产品组编号',
          field: 'productGroupCode',
          slots: {
            default: 'detail'
          }
        },
        {
          title: '自定义产品组名称',
          minWidth: 120,
          align: 'center',
          field: 'productGroupName'
        },
        {
          title: '创建人',
          minWidth: 100,
          align: 'center',
          field: 'createName'
        },
        // {
        //   title: '基本单位',
        //   align: 'center',
        //   field: 'meins'
        // },
        {
          title: '创建时间',
          minWidth: 100,
          align: 'center',
          field: 'createTime'
        },
        // {
        //   title: '销售单位',
        //   align: 'center',
        //   field: 'vrkme'
        // },
        {
          title: '更新人',
          minWidth: 100,
          align: 'center',
          field: 'updateName'
        },
        {
          title: '更新时间',
          minWidth: 100,
          align: 'center',
          field: 'updateTime'
        },
        {
          title: '备注',
          minWidth: 100,
          align: 'center',
          field: 'remarks'
        },
        {
          title: '状态',
          align: 'left',
          field: 'status',
          width: 60,
          fixed: 'right',
          minWidth: 80,
          slots: { default: 'update' }
        },
        {
          title: '操作',
          width: 120,
          field: 'action',
          align: 'center',
          fixed: 'right',
          slots: { default: 'action', filterDropdown: 'filterDropdown' }
        }
      ],
      isorter: {
        permflag: 'product_group_page_impl'
      },
      url: {
        list: window._CONFIG['domianURL'] + '/product/cnProductGroup/findPageList',
        detail: window._CONFIG['domianURL'] + '/product/cnProductGroup/getInfo',
        delete: window._CONFIG['domianURL'] + '/product/cnProductGroup/deleteInfo',
        startOrStopUrl: window._CONFIG['domianURL'] + '/product/cnProductGroup/updateStatus',
        deleteBatch: '/product/cnProductGroup/deleteInfo',
        exportXlsUrl: '/test/cn-formDemo/exportXls'

      }

    }
  },

  methods: {
    startorstop: function(status) {
      if (!this.url.startOrStopUrl) {
        this.$message.error('请设置url启用停用!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认修改',
          content: '是否修改选中数据?',
          onOk: function() {
            that.loading = true
            getAction(that.url.startOrStopUrl, { ids: ids, status: status }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    startorstopByid(status, id) {
      let that = this
      this.$confirm({
        title: '确认修改',
        content: '是否' + (status == 3 ? '停用' : '启动') + '选中数据？',
        onOk() {
          that.loading = true
          getAction(that.url.startOrStopUrl, { ids: id, status: status }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.loadData()
              that.onClearSelected()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.loading = false
          })
        },
        onCancel() {
          // that.loadData();
          // that.onClearSelected();
        }
      })
    },
    selectCusttype(value) {
      this.$set(this.queryParam, 'custType', value)
    },
    changeStatus(e, item) {

      if (e) {
        this.startorstopByid(1, item.id)
      } else {
        this.startorstopByid(3, item.id)
      }
    },
    handleAdd() {
      console.log(111, this.$refs.modalForm)
      // let newDate = formatDateYmd(new Date().getTime())
      // ...this.selectionRows, startDate: newDate, endDate: newDate
      this.$refs.modalForm.add()

      this.$refs.modalForm.title = '新增自定义产品组'

      this.$refs.modalForm.disableSubmit = false
    },
    handleEdit: async function(row) {
      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.title = '编辑自定义产品组'
      this.$refs.modalForm.disableSubmit = false
    },

    handleView: async function(row) {
      this.$refs.modalForm.edit(row)
      this.$refs.modalForm.title = '查看自定义产品组'
      this.$refs.modalForm.disableSubmit = true
    },
    getQueryParams() {
      //高级查询器
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)

      param.field = this.getQueryField()
      param.current = this.ipagination.current
      param.size = this.ipagination.pageSize
      delete param.birthdayRange //范围参数不传递后台
      return filterObj(param)
    },
    // initDictConfig() {
    //   console.log("--我才是真的方法!--")
    //初始化字典 - 性别
    // initDictOptions('sex').then((res) => {
    //   if (res.success) {
    //     this.sexDictOptions = res.result;
    //   }
    // });
    // },
    //跳转单据页面
    jump() {
      this.$notification.success('跳转 ： jump')
    },
    onBirthdayChange: function(value, dateString) {
      console.log(dateString[0], dateString[1])
      this.queryParam.birthday_begin = dateString[0]
      this.queryParam.birthday_end = dateString[1]
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter(item => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    initColumns() {
      //权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
      //this.defColumns = colAuthFilter(this.defColumns,'testdemo:');

      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function(item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter(item => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    }
  },
  created() {
    this.initColumns()
  }

}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>